from socket import *
import pymysql


def create_user(user, pwd):
    db = pymysql.connect(user="devil", password="123456", database="dict", charset="utf8")
    cur = db.cursor()
    sql = "insert into users (user, password) values(%s, %s)"
    try:
        cur.execute(sql, [user, pwd])
        db.commit()
        return True
    except:
        db.rollback()
        return False
    cur.close()
    db.close()


def handle_http(conn):
    request = conn.recv(1024).decode()
    if not request:
        return
    info = request.split("\n")[-1]
    tmp = info.split("&")
    user = tmp[0].split("=")[1]
    pwd = tmp[1].split("=")[1]
    print(user, pwd)
    response = "HTTP/1.1 200 OK \r\n"
    response += "Content-Type: text/html\r\n"
    response += "\r\n"
    if create_user(user, pwd):
        response += "Success"
        conn.send(response.encode())
    else:
        response += "Defeat"
        conn.send(response.encode())


def main():
    sock = socket()
    sock.bind(("0.0.0.0", 8001))
    sock.listen()
    conn, addr = sock.accept()
    handle_http(conn)
    conn.close()


if __name__ == '__main__':
    main()
